package com.honour.controller.interfaced;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.honour.service.interfaced.ConvergeInManager;
import com.honour.service.interfaced.FriendInManager;
import com.honour.service.interfaced.UserInManager;
import com.honour.service.interfaced.impl.CircleInService;
import com.honour.service.interfaced.impl.EnergyInService;
import com.honour.service.interfaced.impl.ReplyInService;
import com.system.controller.base.BaseController;
import com.system.util.AppUtil;
import com.system.util.Const;
import com.system.util.FTPUtils;
import com.system.util.MapDistance;
import com.system.util.PageData;
import com.system.util.Tools;
import com.system.util.ToolsUtil;
import com.system.util.drools.DroolsFactory;

/**
 @Function
 @Author zhaozhenhua
 @Date   2017年12月6日
*/

@Controller
@RequestMapping(value="/appcirclein")
public class CircleInController extends BaseController{
	
	@Resource(name="circleInService")
	private CircleInService circleInService;
	
	@Resource(name="friendinService")
	private FriendInManager friendinService;
	
	@Resource(name="replyinService")
	private ReplyInService replyinService;
	
	@Resource(name="userinService")
	private UserInManager userinService;
	
	@Resource(name="energyInService")
	private EnergyInService energyInService;
	
	@Resource(name="convergeinService")
	private ConvergeInManager coninService;
	
	public static String topic_id="";
	
	/**
	 * 添加我的圈子
	 * @Author zhaozhenhua
	 * @date   2017年12月6日
	 * @return
	 */
	@RequestMapping(value="/addcircle")
	@ResponseBody
	public Object addFriend(MultipartHttpServletRequest mreq,HttpServletResponse resp,HttpServletRequest request,
			String HONOURUSER_ID,String CONTENT,String TOPIC_ID,String TITLE){
		logBefore(logger, "添加我的圈子");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		String circleimgs="";
		try{
			if(Tools.checkKey("CIRCLEADD", pd.getString("FKEY"))){	//检验请求key值是否合法
					List<MultipartFile> fileList = mreq.getFiles("fileList");
					// 创建一个通用的多部分解析器.  
			        //CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
			        // 设置编码  
			        //commonsMultipartResolver.setDefaultEncoding("utf-8");  
			        // 判断是否有文件上传  
			        //if (commonsMultipartResolver.isMultipart(request)){
			        	for (MultipartFile file : fileList) {
			        		if (file!=null&&file.getOriginalFilename().length()!=0&&file.getSize()!= 0) {
			        			//获得UUID之后的文件名
			        			String imgname=getUniqueFileName(file.getOriginalFilename());
			        			InputStream in = file.getInputStream();
			        			//获得文件全名
			        			try {
			        				resp.setCharacterEncoding("UTF-8");
			        				//resp.getWriter().write(filePath+";");
			        				//根据txt文件读取ftp工具类上传需要的参数
			        				String updeploy = Tools.readTxtFileAll(Const.UPDOWNLOADPATH, "UTF-8");
			        				String[] split = updeploy.split(",");
			        				//第一个参数为  图片服务器的地址
			        				//第二个参数为  图片服务器接口
			        				//第三/四个参数为  FTP服务器的登录用户名和密码
			        				//通过工具类获取图片服务器地址
			        				String imgpath = Tools.readTxtFileAll(Const.IMAGEPATH, "UTF-8");
			        				String path="circleimgs";
			        				FTPUtils.uploadFile(split[0], Integer.parseInt(split[1]), split[2], split[3], path, imgname, in);
			        				circleimgs+=","+imgpath+path+"/"+imgname;
			        			} catch (Exception e) {
			        				e.printStackTrace();
			        			}
			        		}
			            }
						if(circleimgs!=null&&circleimgs.length()!=0){
							pd.put("SHOWIMAGES", circleimgs.substring(1));
						}else{
							pd.put("SHOWIMAGES", "");
						}
					pd.put("CIRCLE_ID", this.getSnowId());
					//发布时间
					Date date = new Date();
					String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
					pd.put("PUBLISHTIME", format);
					pd.put("HONOURUSER_ID", HONOURUSER_ID);
					pd.put("CONTENT", CONTENT);
					if(topic_id!=null&&topic_id!=""){
						TOPIC_ID=topic_id;
					}
					pd.put("TOPIC_ID", TOPIC_ID);
					pd.put("TOPIC_TITLE",TITLE);
					circleInService.save(pd);
					topic_id="";
					result = (null == pd) ?  "02" :  "01";
//				}else {
//					result = "03";
//				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	/**
	 * 遍历获取我和我关注的好友的所有圈子并根据时间排序
	 * @Author zhaozhenhua
	 * @date   2017年12月6日
	 * @return
	 */
	@RequestMapping(value="/circlelist")
	@ResponseBody
	public Object getFriendList(){
		logBefore(logger, "遍历获取我和我关注的好友的所有圈子并根据时间排序");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
	    ArrayList<String> ids= new ArrayList<>();
		String result = "00";
		try{
			if(Tools.checkKey("CIRCLELIST", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("sDistance", pd)){	//检查参数
					//获取我关注的所有好友
					pd.put("FRIENDID", "00");
					List<PageData> friendList = friendinService.getFriendList(pd);
					for (PageData pdData : friendList) {
						//将用户的id保存到数组总
						ids.add(pdData.getString("HONOURUSER_ID"));
					}
					//将我的id保存到集合中
					ids.add(pd.getString("HONOURUSER_ID"));
					pd.put("ids", ids);
					//遍历获取我和我关注的好友的所有圈子并根据时间排序
					List<PageData> list = circleInService.getAllCircleListByIds(pd);
					//获取点赞数和评论数
					PageData dotp=new PageData();
					for (PageData pageData : list) {
					    ToolsUtil.putImgstoArray(pageData, "SHOWIMAGES");
						dotp.put("CIRCLE_ID", pageData.get("CIRCLE_ID"));   //查看的圈子id
						dotp.put("HONOURUSER_ID", pd.get("HONOURUSER_ID")); // 我的id
						PageData p=circleInService.getDotAgreeMy(dotp);
						if(p!=null){
							pageData.put("STATUS", "1");  //1为点赞
						}else{
							pageData.put("STATUS", "0");  //0为没有点过赞
						}
					}
					if (list.size()!=0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ?  "02" :  "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	/**
	 * 点赞
	 * @Author zhaozhenhua
	 * @date   2017年12月6日
	 * @return
	 */
	@RequestMapping(value="/dotAgree")
	@ResponseBody
	public Object dotAgree(){
		logBefore(logger, "点赞");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("DOTAGREE", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("dotAgree", pd)){	//检查参数
					//给圈子中心作品点赞
					if(pd.getString("CIRCLE_ID")!=null&&!"".equals(pd.getString("CIRCLE_ID"))){
						PageData p = circleInService.getDotAgreeMy(pd);
						//之前没有点过赞
						if(p==null){
							pd.put("DOTAGREE_ID", this.getSnowId());
							//点赞时间
							Date date = new Date();
							String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
							pd.put("AGREETIME", format);
							circleInService.saveDotAgree(pd);
							//修改点赞数量
							PageData circle = circleInService.getCircleById(pd);
							Integer AGREECOUNT=circle.getInterger("AGREECOUNT")+1;
							circle.put("AGREECOUNT", AGREECOUNT);
							circleInService.edit(circle);
							//使用Drools规则
							PageData energyScore = userinService.getEnergyScore(pd);
							Integer energy = energyInService.getDotAgreeScore(pd);
							energyScore.put("energy", energy);
							DroolsFactory.excuteDrools(energyScore);
							userinService.updEnergyScore(energyScore);
						}
						result = (null != p) ?  "02" :  "01";
					}
					//给评论或回复点赞
					if(pd.getString("COMMENT_ID")!=null&&!"".equals(pd.getString("COMMENT_ID"))){
						PageData p = circleInService.getComDotAgreeMy(pd);
						//之前没有点过赞
						if(p==null){
							pd.put("DOTAGREE_ID", this.getSnowId());
							//点赞时间
							Date date = new Date();
							String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
							pd.put("AGREETIME", format);
							circleInService.saveComDotAgree(pd);
							//修改点赞数量
							PageData commnet = circleInService.getCommentById(pd);
							if("1".equals(pd.getString("STATUS"))){    //如果是正赞
								Integer DOTAGREECOUNT=commnet.getInterger("DOTAGREECOUNT")+1;
								commnet.put("DOTAGREECOUNT", DOTAGREECOUNT);
							}else {                                    //否则为负赞   
								Integer DISAGREECOUNT=commnet.getInterger("DISAGREECOUNT")+1;
								commnet.put("DISAGREECOUNT", DISAGREECOUNT);
							}
							circleInService.editComment(commnet);
							//使用Drools规则
							PageData energyScore = userinService.getEnergyScore(pd);
							Integer energy = energyInService.getDotAgreeScore(pd);
							energyScore.put("energy", energy);
							DroolsFactory.excuteDrools(energyScore);
							userinService.updEnergyScore(energyScore);
						}
						result = (null != p) ?  "02" :  "01";
					}
					//获取点赞分值
	//				Integer score = energyInService.getDotAgreeScore(pd);
					//获取原始分值
//					PageData energyScore = userinService.getEnergyScore(pd);
//					Integer INTERACTSCORE=energyScore.getInterger("INTERACTSCORE")+score;
//					pd.put("INTERACTSCORE", INTERACTSCORE);
//					userinService.updEnergyScore(pd);
					
//					PageData energyScore = userinService.getEnergyScore(pd);
//					Integer score = energyInService.getDotAgreeScore(pd);
//					energyScore.put("score", score);
//					DroolsFactory.excuteDrools(energyScore);
//					userinService.updEnergyScore(pd);
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 添加评论到用户圈子
	 * @Author zhaozhenhua
	 * @date   2017年12月7日
	 * @return
	 */
	@RequestMapping(value="/addcomment")
	@ResponseBody
	public Object addComment(){
		logBefore(logger, "添加评论到用户圈子");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("COMMENTADD", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("addComment", pd)){	//检查参数
					pd.put("COMMENT_ID", this.getSnowId());
					//发布时间
					Date date = new Date();
					String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
					pd.put("COMMENTTIME", format);
					circleInService.saveComment(pd);
					//修改评论数量
					PageData circle = circleInService.getCircleById(pd);
					Integer COMMENTCOUNT=circle.getInterger("COMMENTCOUNT")+1;
					circle.put("COMMENTCOUNT", COMMENTCOUNT);
					circleInService.edit(circle);
					result = (null == pd) ?  "02" :  "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 通过圈子ID获取所有评论
	 * @Author zhaozhenhua
	 * @date   2017年12月7日
	 * @return
	 */
	@RequestMapping(value="/commentlist")
	@ResponseBody
	public Object getCommentList(){
		logBefore(logger, "通过圈子ID获取所有评论");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("COMMENTLIST", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("commentList", pd)){	//检查参数
					List<PageData> list = circleInService.getCommentListById(pd);
					//根据评论ID获评论的点赞数
					for (PageData p : list) {
						PageData user = new PageData();
						if(p.getString("REPLYHONOURUSER_ID")!=null&&p.getString("REPLYHONOURUSER_ID").length()!=0){  //不为空如果是回复,为空时评论
							user.put("HONOURUSER_ID", p.getString("REPLYHONOURUSER_ID"));   
							PageData user1 = userinService.getUserById(user);
							p.put("REPLYNICKNAME", user1.getString("NICKNAME"));
						}else {
							p.put("REPLYNICKNAME", "");
						}
						p.put("dotAgreeCount", p.getInterger("DOTAGREECOUNT"));   //正赞次数
						p.put("lossAgreeCount", p.getInterger("DISAGREECOUNT"));  //负赞次数
					}
					if (list.size()!=0) {
						map.put("pd", list);
					}
					result = (0 == list.size()) ?  "02" :  "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 多文件上传辅助方法
	 * @param originalFileName
	 * @return
	 * @Author 于泓磊
	 */
	private String getUniqueFileName(String originalFileName) {
		String ext=null;
		if(originalFileName.indexOf(".")!=-1){
			ext = originalFileName.substring(originalFileName.lastIndexOf("."),originalFileName.length());
		}else{
			ext="."+originalFileName;
		}
		UUID uuid = UUID.randomUUID();
		String uniqueFileName = uuid+ext;
		String replace=uniqueFileName.replace("-", "");
		return replace;

	}
	
	/**
	 *	根据经纬度计算距离
	 * @param args
	 * @throws Exception
	 */
	public Object getDistance(PageData pd){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success",distance="";
		try {
			PageData p = coninService.getDistanceUserAndUser(pd);
			distance  = MapDistance.getDistance(p.getString("MYUSERLONGITUDE"),p.getString("MYUSERLATITUDE"),p.getString("USERLONGITUDE"),p.getString("USERLATITUDE"));
		} catch (Exception e) {
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		map.put("distance", distance);			//距离
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 添加话题
	 * @Author zhaozhenhua
	 * @date   2017年12月28日
	 * @return
	 */
	@RequestMapping(value="/addtopic")
	@ResponseBody
	public Object addTopic(String HONOURUSER_ID,String TITLE ){
		logBefore(logger, "添加话题");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("TOPICADD", pd.getString("FKEY"))){	//检验请求key值是否合法
				    String TOPIC_ID = this.getSnowId();
				    topic_id=TOPIC_ID;
					pd.put("TOPIC_ID", TOPIC_ID);
					//发布时间
					Date date = new Date();
					String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
					pd.put("CREATETIME", format);
					pd.put("HONOURUSER_ID", HONOURUSER_ID);
					pd.put("DESCRIPTION", "");
					pd.put("TITLE", TITLE);
					circleInService.addTopic(pd);
					result = "01";
				}else {
					result = "03";
				}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 根据话题查询 
	 * @Author zhaozhenhua
	 * @date   2017年12月28日
	 * @return
	 */
	@RequestMapping(value="/gettopicbytitle")
	@ResponseBody
	public Object getTopicByTitle(){
		logBefore(logger, "根据话题查询");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("TOPICBYTITLE", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("getTopicByTitle", pd)){	//检查参数
					PageData topic = circleInService.getTopicByTitle(pd);
					result = (null == topic) ?  "02" :  "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 获取话题列表(含模糊查询) 
	 * @Author zhaozhenhua
	 * @date   2017年12月28日
	 * @return
	 */
	@RequestMapping(value="/gettopiclist")
	@ResponseBody
	public Object getTopicList(){
		logBefore(logger, "获取话题列表(含模糊查询)");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("TOPICLIST", pd.getString("FKEY"))){	//检验请求key值是否合法
					List<PageData> list = circleInService.getTopicList(pd);
					if(!list.isEmpty()){
						map.put("pd", list);
					}
					result = (0 == list.size()) ?  "02" :  "01";
				}else {
					result = "03";
				}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
}
